package com.loyal.camerax.config

import android.graphics.Bitmap
import android.graphics.Matrix
import com.loyal.camerax.utils.ImageUtil
import java.io.File
import java.io.FileOutputStream

data class PhotoConfig(
    val horizontalMirror: Boolean = false,
    val verticalMirror: Boolean = false,
    val rotationAngle: Float = 0f,
    val enableCrop: Boolean = false,//裁剪
    val enableCompress: Boolean = false, //压缩
    val imageFile: File? = null
) {

    companion object {

        @JvmStatic
        fun PhotoConfig.saveImageByteArray(data: ByteArray): Boolean {
            val compressConfig = CompressConfig(enable = true, byteDate = data)
            return try {
                val compressBitmap = ImageUtil.byteArrayToBitmap(compressConfig)
                val rotateBmp = createBitmap(compressBitmap)
                val success = saveBitmap(rotateBmp)
                rotateBmp?.let {
                    if (!it.isRecycled) {
                        it.recycle()
                    }
                }

                success
            } catch (e: Exception) {
                false
            }
        }

        @JvmStatic
        fun PhotoConfig.saveBitmap(bitmap: Bitmap?): Boolean {
            val imageFile = this.imageFile
            if (null == bitmap || null == imageFile) return false
            val jpgFile = imageFile
            try {
                FileOutputStream(jpgFile).use { outputStream ->
                    outputStream.write(
                        ImageUtil.compress(bitmap, this.enableCompress)
                    )
                    outputStream.flush()
                    outputStream.close()
                    return true
                }
            } catch (e: Exception) {
                return false
            }
        }

        /**
         * Bitmap创建
         */
        @JvmStatic
        fun PhotoConfig.createBitmap(bitmap: Bitmap?): Bitmap? {
            try {
                bitmap?.let {
                    val width = it.width
                    val height = it.height
                    val matrix = Matrix()
                    // 以当前自己的原点旋转多少度
                    matrix.setRotate(this.rotationAngle, width / 2f, height / 2f)
                    if (this.verticalMirror) matrix.postScale(1f, -1f);   //镜像垂直翻转
                    if (this.horizontalMirror) matrix.postScale(-1f, 1f) //镜像水平翻转
                    val rotateBmp = Bitmap.createBitmap(it, 0, 0, width, height, matrix, true)
                    if (rotateBmp != it) it.recycle()
                    return rotateBmp
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return null
        }
    }
}
